<?php

namespace Lib;

use Models\Services\WxCoupon;

final class Tool {

    static public function clientIp($ip2long = false) {
        if (isset($_SERVER)) {
            if (isset($_SERVER['HTTP_X_REAL_IP'])) {
                $ip = $_SERVER ['HTTP_X_REAL_IP'];
            } else {
                if (isset($_SERVER ['HTTP_X_FORWARDED_FOR'])) {
                    $ip = array_pop(explode(',', $_SERVER ['HTTP_X_FORWARDED_FOR']));
                } elseif (isset($_SERVER ['HTTP_CLIENT_IP'])) {
                    $ip = $_SERVER ['HTTP_CLIENT_IP'];
                } else {
                    $ip = $_SERVER ['REMOTE_ADDR'];
                }
            }
        } else {
            if (getenv('HTTP_X_REAL_IP')) {
                $ip = getenv('HTTP_X_REAL_IP');
            } else {
                if (getenv('HTTP_X_FORWARDED_FOR')) {
                    $ip = array_pop(explode(',', getenv('HTTP_X_FORWARDED_FOR')));
                } elseif (getenv('HTTP_CLIENT_IP')) {
                    $ip = getenv('HTTP_CLIENT_IP');
                } else {
                    $ip = getenv('REMOTE_ADDR');
                }
            }
        }

        if ($ip === '::1') {
            $ip = '127.0.0.1';
        }

        //return $ip2long ? ip2long($ip) : long2ip(ip2long($ip));
        return $ip2long ? ip2long($ip) : $ip;
    }

    public static function createOrderNo() {
        //return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        //return date('Ymd') . sprintf('%05d', substr(time(),-5)) . sprintf('%05d', substr(microtime(),2,5)) . sprintf('%04d', rand(0, 9999)); //18
        $no = date('ymd') . sprintf('%05d', (time() + 28800) % 86400) . sprintf('%04d', substr(microtime(), 2, 4)) . sprintf('%04d', rand(0, 9999)); //18

//        $redis = \Phalcon\Di::getDefault()->get('redis');
//        $key   = "order_no_unique";
//
//        if (!$redis->exists($key) || !$redis->hExists($key, $no)) { // 不存在
//            $redis->hSet($key, $no, 1);
//            return $no;
//        }
//        return self::createOrderNo();
        return md5($no);
    }

    public static function productNo($sum) {
        return sprintf(Consts::IOS_PRODUCT_ID . '%sgold', $sum);
    }

    public static function arrToObj($arr) {
        if (is_array($arr)) {
            $obj = new \stdClass();

            foreach ($arr as $key => $val) {
                $obj->$key = $val;
            }
        } else {
            $obj = $arr;
        }

        return $obj;
    }

    /**
     * 取得毫秒时间戳
     * @return float
     */
    public static function milliSecond() {
        list($t1, $t2) = explode(' ', microtime());
        return (string)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
    }

    public static function cdnUrl($url) {
        if (empty($url)) {
            return $url;
        }

        $config   = \Phalcon\DI::getDefault()->get('config');
        $hostName = $config->application->picStaticUrl;
        $url      = $hostName . $url;

        $extension = pathinfo($url, PATHINFO_EXTENSION);

        if (in_array($extension, ["jpg", "png"])) {
            $url = $url . "?imageslim";
        }

        return $url;
    }

    public static function cdnContent($content) {
        if (empty($content)) {
            return $content;
        }

        $config   = \Phalcon\DI::getDefault()->get('config');
        $hostName = $config->application->picStaticUrl;
        //$hostName = "http://camera.jmuit.com";

        $content = str_replace(' src="/upload/ckfinder', ' src="' . $hostName . '/upload/ckfinder', $content);
        $content = str_replace('.jpg" ', '.jpg?imageslim" ', $content);
        $content = str_replace('.png" ', '.png?imageslim" ', $content);

        return $content;
    }

    /**
     * 是否是邮箱地址
     *
     * @param string $email
     * @return boolean
     */
    static public function email($email) {
        return ($email === \filter_var($email, \FILTER_VALIDATE_EMAIL)) ? true : false;
    }

    /**
     * 是否是有效的大陆手机号码
     *
     * @param string|int $num 号码
     * @return boolean
     */
    static public function mobileNum($num) {
        $num = trim($num);

        // 是否是11位
        if (11 !== strlen($num)) {
            return false;
        }

        $pattern = '/^1[3|4|5|7|8|9][0-9]{9}$/';

        return \preg_match($pattern, $num) ? true : false;
    }

    /**
     * 是否是有效的QQ号码
     *
     * @param string|int $num
     * @return boolean
     */
    static public function qqNum($num) {

        $pattern = '/^[1-9][0-9]{4,9}$/';

        return \preg_match($pattern, $num) ? true : false;
    }

    /**
     * url正则验证
     * @param string $url
     * @return boolean
     */
    static public function url($url) {
        $match = '/^(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;\+#]*[\w\-\@?^=%&amp;\+#])?/';
        return preg_match($match, $url) ? true : false;
    }

//    static public function couponNo() {
//        $no          = sprintf('%07d', uniqid());
//        $couponModel = WxCoupon::findFirstByCoupon($no);
//
//        if (!$couponModel instanceof WxCoupon) {
//            return $no;
//        }
//
//        return self::couponNo();
//    }

    public static function FromXml($xml) {
        if(!$xml) {
            return "";
        }
        //将XML转为array
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    }

    public static function sign($appKey, $appSecret, $time) {
        return md5($appKey . $appSecret . $time);
    }


    public static function unicodeDecode($unicode_str){
        $json = '{"str":"'.$unicode_str.'"}';
        //print_r($json);
        $arr = json_decode($json,true);
        if(empty($arr)) return '';
        return $arr['str'];
    }

    // \"->"  "{->{   "}->}
    public static function sqlJsonHandle($str){
//        $str = str_replace('\"', '"', $str);
//        $str = str_replace('"{', '{', $str);
//        $str = str_replace('"}', '}', $str);
        // lvsong暂时关闭
//        $str = str_replace('"[', '[', $str);
//        $str = str_replace(']"', ']', $str);

        return $str;
    }

}
